package com.bschlearn.group.common.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bschlearn.group.message.BaseRsp;

@Aspect
@Component
public class HttpAspect {
	
	// 实例化log
	private final static Logger log = LoggerFactory.getLogger(HttpAspect.class);
	
	/**
	 * 设置切面
	 */
	@Pointcut("execution (public * com.bschlearn.group.controller.*.*(..))")
	public void pointCut() {
		
	}
	
	/**
	 * 在进入方法前处理
	 */
	@Before("pointCut()")
	public void doBefore(JoinPoint joinPoint) {
		// 获取请求
		ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		
		// 获取url
		log.info("url={}",request.getRequestURL());
		
		// 获取method
		log.info("method={}",request.getMethod());
		
		// 获取ip
		log.info("ip={}",request.getRemoteAddr());
		
		// 获取类方法
		log.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
				
		// 获取参数
		log.info("args={}",joinPoint.getArgs());
		
	}
	
	@After("pointCut()")
	public void doAfter() {
		log.info("已经退出方法了");
	}
	
	// 处理返回信息
	@AfterReturning(returning = "obj",pointcut = "pointCut()")
	public void doAfterReturning(Object obj) {
		// 可以进行统一信息的封装
		BaseRsp ok = BaseRsp.ok(obj);
		log.info(ok.toString());
	}

}
